package com.lcache.core.listener;

import com.alibaba.fastjson.JSON;
import com.lcache.common.api.ApiResponse;
import com.lcache.core.service.Level1Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.apache.rocketmq.client.apis.consumer.MessageListener;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @program: lcache
 * @description: 缓存监听类
 * @author: Alex Wu
 * @createDate: 2025-04-22 17:38
 **/
@Slf4j
public class CacheListener implements MessageListener {

    private final Level1Cache level1Cache;
    public CacheListener(Level1Cache level1Cache) {
        this.level1Cache = level1Cache;
    }

    @Override
    public ConsumeResult consume(MessageView messageView) {
        String messageId = messageView.getMessageId().toString();
        ByteBuffer body = messageView.getBody();
        String bodyStr = StandardCharsets.UTF_8.decode(body).toString();
        log.info("Received MQ message: id={}, body={}", messageId, bodyStr);

        String[] split = bodyStr.split(":");
        if(split.length == 2){
            level1Cache.updateFromMQ(split[0], split[1]);
        }
        return ConsumeResult.SUCCESS;
    }
}
